// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
import compression from 'vite-plugin-compression'
import proxyObj from './vite.proxy'
//自动导入ui-组件 比如说ant-design-vue  element-plus等
import Components from 'unplugin-vue-components/vite';
//ant-design-vue
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers"

export default defineConfig(({ command, mode }) => {
  let env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vue({
        template: {
          compilerOptions: { isCustomElement: (tag) => tag.startsWith('wc-') }
        },
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
      compression({
        algorithm: 'gzip', // 指定压缩算法为gzip,[ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: '.gz', // 指定压缩后的文件扩展名为.gz
        threshold: 10240, // 仅对文件大小大于threshold的文件进行压缩，默认为10KB
        deleteOriginFile: false, // 是否删除原始文件，默认为false
        filter: /\.(js|css|json|html|ico|svg)(\?.*)?$/i, // 匹配要压缩的文件的正则表达式，默认为匹配.js、.css、.json、.html、.ico和.svg文件
        compressionOptions: { level: 9 }, // 指定gzip压缩级别，默认为9（最高级别）
        verbose: true, //是否在控制台输出压缩结果
        disable: false, //是否禁用插件
      }),
      Components({
        //ant-design-vue   importStyle = false 样式就没了
        resolvers: [AntDesignVueResolver({ importStyle: false, resolveIcons: true })],
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve('./src'), // 相对路径别名配置，使用 @ 代替 src
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData:
            '@import "@/styles/mixin.scss";@import "./src/styles/variable.scss";',
        },
      },
    },
    server: {
      port: 3280,
      host: true,
      open: false,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_SERVE,
          changeOrigin: true,
          rewrite: (path) => {
            let baseUrl = env.VITE_APP_BASE_API
            let regex = new RegExp(`^${baseUrl}/`)
            return path.replace(regex, '')
          },
        },
        ...proxyObj
      },
    },
    build: {
      sourcemap: command === 'build' ? false : 'inline',
      outDir: 'dist', //指定输出目录
      assetsDir: 'assets', //指定静态资源存储目录(相对于outDir)
      // 将js、css文件分离到单独文件夹
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules/vue')) {
              return 'vue-vendor'
            }
            if (id.includes('node_modules/lodash')) {
              return 'lodash-vendor'
            }
            if (id.includes('node_modules/ant-design-vue')) {
              return 'ant-vendor'
            }
            // 通用逻辑  
            if (id.includes('node_modules/.pnpm')) return;
            if (id.includes('node_modules/')) {
              const packageName = id.split('node_modules/')[1].split('/')[0]
              return packageName
            }
            return undefined
          },
        },
      },
      chunkSizeWarningLimit: 1000, // 单个模块文件大小限制1000KB
      terserOptions: {
        // 清除代码中console和debugger
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
  }
})
